<?php
$isReloadable = false;
require_once("../../../pers/inc.config.php");
require_once('../../_inc/inc.session.php');
require_once('../../_inc/funct.html.php');
require_once('../_inc/funct.cerBil.php');
require_once('../../_inc/funct.tabDati.php');

$sSql = "SELECT sd.id_set_dati, sd.descr, sd.cod_set_dati "
	." FROM rgl_set_dati sd "
	." WHERE fonte_bil = 'cerved' "
	." ORDER BY sd.cod_set_dati";
$objDB->query($sSql,'selATD');
$aSD = array();
while($acSD = $objDB->fetch('selATD')) {
	reqDef('id_set_dati',$acSD['id_set_dati']);
	$aSD[$acSD['id_set_dati']] = $acSD['cod_set_dati']." - ".$acSD['descr'];
}
if (count($aSD)==0) {
	backOnErr('nessuna tabella bilcee definita');
}
$aInfo = null;
if (reqVar('azione') == 'carica') {
	$msgPag = caricaBil($aInfo);
} 

$sCmdR = '';
$sCmdR .= "<a class='cmd1' href='javascript:document.frm1.submit();'>carica</a>";
$sCmdR .= cmdTorna('torna');

testaHtml('', $msgPag, 'ratg');
?>
<table border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="right">
			<? echo $sCmdR; ?>
      </td>
   </tr>
</table>
<?
echo getHtmlForm('frm1','',array('enctype'=>true));
echo getHtmlHidden('azione','carica');
echo getHtmlHidden('xsn',XSN);
?>
<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
	<?=getHtmlRigaRif();?>
   <tr>
      <td class="lab1" colspan='20' align='center'>Coordinate bilancio</td>
   </tr>
   <tr>
      <td class="lab1" colspan='4' align='left'>Cod. CCIAA (ppnnnn)</td>
      <td class="txt1" colspan='3' align='left'>
      	<? echo getHtmlText('id_azienda', 16);?>
      </td>
      <td class="lab1" colspan='2' align='left'>Anno</td>
      <td class="txt1" colspan='2' align='left'>
      	<? 
      	reqDef('anno',date('Y')-1);
      	for($a=date('Y')+2;$a>date('Y')-20;$a--) $aAnni[$a] = $a;
      	echo getHtmlSelect('anno', $aAnni);?>
      </td>
      <td class="lab1" colspan='1' align='left'>Set dati</td>
      <td class="txt1" colspan='5' align='left'>
<? 
echo getHtmlSelect('id_set_dati', $aSD);
?>
      </td>
      <td class="txt1" colspan='3' align='left'>
      	<? echo getHtmlCheckBox('ricarica', 'S');?> ri-carica
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='3' align='left'>Descr.</td>
      <td class="txt1" colspan='17' align='left'>
      	<? echo getHtmlText('descr', 80,80);?>
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='5' align='left'>Nota</td>
      <td class="txt1" colspan='15' align='left'>
      	<? echo getHtmlTextArea('nota', 100,5);?>
      </td>
   </tr>
   <tr>
      <td class="cmd1" align="right" colspan='20'>
         <? echo $sCmdR; ?>
      </td>
   </tr>
<?
if ($aInfo != null) {$aDati
?>
   <tr>
      <td class="lab1" align="center" colspan='20'>Dati</td>
   </tr>
   <tr>
      <td class="lab1" align="left" colspan='3'>Azienda</td>
      <td class="txt1" align="left" colspan='10'><?=$aInfo['anag']['rag_soc']?></td>
      <td class="lab1" align="left" colspan='3'>Cod CCIAA</td>
      <td class="txt1" align="left" colspan='4'><?=$aInfo['anag']['id_azienda']?></td>
   </tr>
   <tr>
      <td class="lab1" align="left" colspan='3'>Residenza</td>
      <td class="txt1" align="left" colspan='10'><?=$aInfo['anag']['comune']." (".$aInfo['anag']['prov'].")"?></td>
      <td class="lab1" align="left" colspan='3'>Cod.fisc.</td>
      <td class="txt1" align="left" colspan='4'><?=$aInfo['anag']['cod_fisc']?></td>
   </tr>
   <tr>
      <td class="lab1" align="left" colspan='3'>Settore</td>
      <td class="txt1" align="left" colspan='17'><?=$aInfo['anag']['cod_att']?></td>
   </tr>
<?
$aGeDati = getGerarcTabDati('BILCEE');
//dbg_($aGeDati);
//dbg_($aDati);
foreach($aGeDati as $codX => $aX) {
	echoDato($codX,$aX,$aInfo,0);
}
?>
</table>
<?
}
echo "</form>\n";require_once('../../_inc/funct.tabDati.php');

codaHtml();
exit();


function echoDato($codX, $aX, &$aInfo, $liv) {
	$aCSez = array(''=>'-- non sezione --');
	$aCSez['spatt'] = 'Stato patrimoniale - Attivo';
	$aCSez['sppas'] = 'Stato patrimoniale - Passivo';
	$aCSez['cecon'] = 'Conto economico';
	$aCSez['altro'] = 'Altri dati';
	$aCSez['calco'] = 'Dati calcolati';
	
	if ($aX['attr']['cod_sez']!='') {
		echo "<tr><td class='txt1'align='center' colspan='20'><b>".$aCSez[$aX['attr']['cod_sez']]."</b></td><tr>\n";
	}
	$valX = (isset($aInfo['dati'][$codX])) ? number_format($aInfo['dati'][$codX],2,',','.') : '';
	echo "<tr><td class='txt1' colspan='16'>".str_repeat("&nbsp;",$liv*8)
		."<a href='datoVis.php?cd=$codX&xsn=".XSN."' class='txt1'>$codX</a> - ".$aX['attr']['descr']
		."</td><td class='txt1' align='right' colspan='4'>$valX</td><tr>\n";
	foreach($aX['figli'] as $codY => $aY)  {
		echoDato($codY, $aY, $aInfo, $liv+1);
	}
}
//dbg_($aGeDati);

function caricaBil(&$aInfo) {
	global $objDB,$objSess;
	$msg = '';
	$_REQUEST['id_azienda'] = strtoupper(trim(reqVar('id_azienda')));
	if (reqVar('id_azienda')=='') {
		$msg .= _t("Codice obbligatorio")."<br>";
	}
	if (preg_match("/[^0-9]/",reqVar('anno')) 
	|| reqVar('anno') < 2000 || reqVar('anno') > 2030) {
		$msg .= _t("anno obbligatorio numerico tra 2000 e 2030")."<br>";
	}	
	if ($msg != '') return $msg;
	
	$codCCIAA = reqVar('id_azienda');
	$aInfo = array('anag'=>array('id_azienda'=>$codCCIAA),'dati'=>array());
	$dataRif = reqVar('anno')."-12-31";
	$sSql = "SELECT b.id_bil, b.str_dati, a.*  FROM rgl_bilancio b "
		." LEFT JOIN rgl_azienda a ON a.id_azienda = b.id_azienda "
		." WHERE b.id_azienda = '$codCCIAA' AND b.data_rif = '$dataRif' "
		." AND b.id_set_dati = ".reqVarInt('id_set_dati')
		;
	$objDB->query($sSql, 'readBil');
	$aRec = $objDB->fetch('readBil');
	if (reqVar('ricarica') != 'S' && $aRec) {
		$aInfo['anag']['id_azienda'] = $aRec['id_azienda'];
		$aInfo['anag']['rag_soc'] = $aRec['id_azienda'];
		$aInfo['anag']['comune'] = $aRec['prov'];
		$aInfo['anag']['prov'] = $aRec['prov'];
		$aInfo['anag']['cod_fisc'] = $aRec['cod_fisc'];
		$aInfo['anag']['cod_att'] = $aRec['cod_att'];
		$aInfo['anag']['attivita'] = $aRec['attivita'];
		$aInfo['dati'] = unserialize($aRec['str_dati']);
		return _t('Bilancio gia\' caricato')."<br>"; 
	}
	$sXml = '';
	$mess = getCerBilXml($codCCIAA,$dataRif,$sXml);
	if ($mess!='') return $mess;
	$mess = cerBilXml2aInfo($sXml,$aInfo);
	if ($mess!='') return $mess;

	if (reqvarTrim('descr')=='') {
		$_REQUEST['descr'] = "Bilancio da C.B.";
	}
	
	//inserisce/aggiorna anag 
	$sSql = "SELECT a.*  FROM rgl_azienda a "
		." WHERE a.id_azienda = '$codCCIAA'";
	$objDB->query($sSql, 'readBil');		
	if ($aAnag = $objDB->fetch('readBil')) {
		$sSql = "UPDATE rgl_azienda SET rag_soc = '".addslashes($aInfo['anag']['rag_soc'])."' "
			.",comune = '".addslashes($aInfo['anag']['comune'])."'"
			.",prov = '".addslashes($aInfo['anag']['prov'])."'"
			.",cod_fisc = '".addslashes($aInfo['anag']['cod_fisc'])."'"
			.",cod_att = '".addslashes($aInfo['anag']['cod_att'])."'"
			.",attivita = '".addslashes($aInfo['anag']['attivita'])."'"
			." WHERE id_azienda = '$codCCIAA' "
			;
		//dbg_($sSql);
		$objDB->query($sSql, 'readBil');
	} else {
		$sSql = "INSERT INTO rgl_azienda SET id_azienda = '$codCCIAA' "
			.",rag_soc = '".addslashes($aInfo['anag']['rag_soc'])."' "
			.",comune = '".addslashes($aInfo['anag']['comune'])."'"
			.",prov = '".addslashes($aInfo['anag']['prov'])."'"
			.",cod_fisc = '".addslashes($aInfo['anag']['cod_fisc'])."'"
			.",cod_att = '".addslashes($aInfo['anag']['cod_att'])."'"
			.",attivita = '".addslashes($aInfo['anag']['attivita'])."'"
			;
		$objDB->query($sSql, 'readBil');
	}
	
	if (!$aRec) {
		$sSql = "INSERT INTO rgl_bilancio SET id_azienda = '$codCCIAA' "
			.",data_rif = '$dataRif' "
			.",id_set_dati = ".reqVarInt('id_set_dati')
			.",descr = '".reqVarAS('descr')."' "
			.",nota = '".reqVarAS('nota')."' "
			.",str_dati = '".addslashes(serialize($aInfo['dati']))."'"
			.",file_caricato = '".addslashes($sXml)."'"
			.",stato_lav = 'da verificare' "
			;
		$objDB->query($sSql, 'readBil');
		$idBil = $objDB->lastInsertId('readBil');
		$sSql = "INSERT INTO rgl_bilancio_log SET id_bil = $idBil "
			.",data_ora = '".date('Y-m-d H:i:s')."' "
			.",id_utente = ".intval($objSess->idUtente)
			.",descr_operaz = 'Caricato da C.B.' "
			.",str_dati = '".addslashes(serialize($aInfo['dati']))."'"
			;
		$objDB->query($sSql, 'readBil');
		return 'bilancio caricato';
	} 
	$sSql = "UPDATE rgl_bilancio SET str_dati = '".addslashes(serialize($aInfo['dati']))."'"
			.",id_set_dati = ".reqVarInt('id_set_dati')
			.",file_caricato = '".addslashes($sXml)."'"
			.",descr = '".reqVarAS('descr')."' "
			.",nota = '".reqVarAS('nota')."' "
			.",stato_lav = 'da verificare' "
			." WHERE id_bil = ".$aRec['id_bil'];
	$objDB->query($sSql, 'readBil');
	$sSql = "INSERT INTO rgl_bilancio_log SET id_bil = ".$aRec['id_bil']
		.",data_ora = '".date('Y-m-d H:i:s')."' "
		.",id_utente = ".intval($objSess->idUtente)
		.",descr_operaz = 'Ri-caricato da C.B.' "
		.",str_dati = '".addslashes(serialize($aInfo['dati']))."'"
		;
	$objDB->query($sSql, 'readBil');
	
	return 'bilancio ri-caricato';
	exit();
}
